package net.ib.mtalk.network.task;

import net.ib.mntalk.protocol.Common;
import net.ib.mntalk.protocol.Common.UUIDMsg;
import net.ib.mntalk.protocol.Session.RemoveMessagesReq;
import net.ib.mntalk.protocol.Session.RemoveMessagesRes;
import net.ib.mtalk.constant.HandlerMsgConst;
import net.ib.mtalk.database.helper.ChatDatabaseHelper;
import net.ib.mtalk.network.MethodId.Session;
import net.ib.mtalk.network.TcpEnvelope;
import net.ib.mtalk.util.GpbSupport;
import net.ib.mtalk.util.MTalkLogWriter;
import android.content.Context;
import android.os.Handler;

public class RemoveMessagesTask extends AsyncNetTask {
	
	private RemoveMessagesReq mRemoveMessagesReq;
	
	public RemoveMessagesTask(Context context, Handler handler, RemoveMessagesReq removeMessagesReq){
		super(context, handler);
		this.mRemoveMessagesReq = removeMessagesReq;
	}
	
	@Override
	protected TcpEnvelope onPreExecute() {
		TcpEnvelope rev = new TcpEnvelope.Builder()
			.setType(TcpEnvelope.REQUEST)
			.setMessage(mRemoveMessagesReq)
			.setMethodId(Session.Messaging.RemoveMessage)
			.build();
		return rev;
	}
	
	@Override
	protected void onPostExecute(int resultCode, Object sentObject,
			Object receivedObject) {
		MTalkLogWriter.d("RemoveMessagesTask.onPostExecute() resultCode : " + resultCode);
		if (receivedObject == null) {
			mUiHandler.sendMessageAtFrontOfQueue(mUiHandler.obtainMessage(HandlerMsgConst.HANDLER_UNKNOWN_ERROR));
			return;
		}
		
		TcpEnvelope resultEnvelope = (TcpEnvelope) receivedObject;
		RemoveMessagesRes removeMessagesRes = (RemoveMessagesRes) resultEnvelope.getMessage();
		
		MTalkLogWriter.d("RemoveMessagesTask ResponseCode : " + removeMessagesRes.getResponseCode());
		
		if(removeMessagesRes.getResponseCode() == Common.SUCCESS){
			for(UUIDMsg notiUuid : mRemoveMessagesReq.getNotiUuidList()){				
				ChatDatabaseHelper.deleteMsgWhereView(mContext, GpbSupport.msbOf(notiUuid), GpbSupport.lsbOf(notiUuid));
			}
			mUiHandler.sendMessageAtFrontOfQueue(mUiHandler.obtainMessage(HandlerMsgConst.HANDLER_REMOVE_MESSAGES_SUCCESS));
		} else{
			mUiHandler.sendMessageAtFrontOfQueue(mUiHandler.obtainMessage(HandlerMsgConst.HANDLER_REMOVE_MESSAGES_FAIL));
		}
	}
}
